/**
 * Created by huxia on 2016/12/9.
 */

var express = require('express');
var router = express.Router();
var url = require('url');
var querystring = require('querystring');
var Outcalls = require('../models').Outcall;
var Doctor = require('../models').Doctor;
var Department = require('../models').Department;
var Hospital = require('../models').Hospital;
var User = require('../models').User;
var Appointment = require('../models').Appointment;
var Area = require('../models').Area;
var utils = require('../utils');
var async = require('async');

/*Doctor index*/
router.get('/', function (req, res, next) {
	var list_city = [];
	var list_area = [];
	var list_dept_s = [];

	//默认的地区：北京、北京市、海淀区
	var pid = 2, cid = 52, aid = 502;
	//默认的科室：内科，心血管内科
	var fid = 1, sid = 24, dl = 0;

	var doc_url = '';

	var loca = req.session.location;
	//根据session中的信息更新位置信息
	if (loca != undefined && loca.pid != undefined && loca.cid != undefined && loca.aid != undefined) {
		pid = loca.pid;
		cid = loca.cid;
		aid = loca.aid;
	}
	else {//根据将当前地区信息更新session
		utils.locationSession(req, res, pid, cid, aid);
		loca = req.session.location;
	}

	var dept = req.session.dept;
	if (dept != undefined && dept.first_level != undefined && dept.second_level != undefined) {
		fid = dept.first_level;
		sid = dept.second_level;
	}
	else{
		utils.deptSession(req, res, fid, sid, dl);
        dept = req.session.dept;
	}

	//在get时,地区信息应当是合法的
	Area.findByPid(pid).then(function (list_city_f) {
		list_city = list_city_f;
		return Area.findByPid(cid);
	}).then(function (list_area_f) {
		list_area = list_area_f;

		return Department.findByPid(fid);
	}).then(function (list_dept_s_f) {
		list_dept_s = list_dept_s_f;

		doc_url = '/doctor/doctor_list_frame?pid=' + pid + '&cid=' + cid + '&aid=' + aid + '&fid=' + fid + '&sid=' + sid + '&dl=' + dl;

		res.render('doctor/find_doctor', {
			title: '找医生',
			user: req.session.user,
			city: list_city,
			area: list_area,
			dept_s:list_dept_s,
			location:loca,
			department:dept,
			doc_list_url: doc_url
		});
	});
}).post('/', function (req, res, next) {
	var pid = parseInt(req.body.p_id);        //省/直辖市的id
	var cid = parseInt(req.body.c_id);        //市的id
	var aid = parseInt(req.body.a_id);        //区\县的id
	var fid = parseInt(req.body.f_id);        //一级科室的id
	var sid = parseInt(req.body.s_id);        //二级科室的id
	var dl = parseInt(req.body.d_level);     //医生等级

	var list_city = [];
	var list_area = [];
	var list_dept_s = [];

	var doc_url = '';

	var capital_id;
	var cap_dept_s_id;
	Area.findByPid(pid).then(function (list_city_f) {//得到当前省份所有市的列表，并将首府设为该表的第一个城市
		list_city = list_city_f;
		capital_id = parseInt(list_city[0].dataValues.area_id);

		return Area.findById(cid);
	}).then(function (city_f) {//如果当前城市所在的省不是当前省，则将当前城市设为当前省的首府
		var parent_id = parseInt(city_f.get("parent_id"));
		if (parent_id !== pid) {
			cid = capital_id;
		}

		return Area.findByPid(cid);
	}).then(function (list_area_f) {//得到当前市的所有地区的列表，并通过aid查找当前地区，如果aid为0，则返回null
		list_area = list_area_f;
		return Area.findById(aid);
	}).then(function (area_f) {//如果当前地区所在的市，如果不是当前市，则将当前地区设为0，意为当前市的所有地区
		if (area_f !== null) {
			var parent_id = parseInt(area_f.parent_id);
			if (parent_id !== cid) {
				aid = 0;
			}
		}

		if (fid != req.session.dept.first_level) {//如果一级科室改变
			sid = 0;
		}

		return Department.findByPid(fid);
	}).then(function (dept_s_f) {//获得当前一级科室所有二级科室的列表
		list_dept_s = dept_s_f;

		var city_json = [];
		var area_json = [];
		var dept_s_json = [];

		//将所有列表转为json格式发送
		list_city.forEach(function (item) {
			city_json.push(item.dataValues);
		});

		list_area.forEach(function (item) {
			area_json.push(item.dataValues);
		});

		list_dept_s.forEach(function (item) {
			dept_s_json.push(item.dataValues);
		});

		//将当前信息放入session
		utils.deptSession(req, res, fid, sid, dl);
		utils.locationSession(req, res, pid, cid, aid);

		//向子页面传递新的url
        doc_url = '/doctor/doctor_list_frame?pid=' + pid + '&cid=' + cid + '&aid=' + aid + '&fid=' + fid + '&sid=' + sid + '&dl=' + dl;
		res.json({
			user: req.session.user,
			city: city_json,
			area: area_json,
			dept_s:dept_s_json,
			doc_list_url:doc_url
		});
	});
});

router.get('/details', function (req, res, next) {
    var doc_id = parseInt(req.query.doc_id);
	if (isNaN(doc_id)) {
		res.redirect('/');
	}
    Doctor.findById(doc_id).then(function (doctor) {
	    var doc_json = {};
	    doc_json.name = doctor.name;
	    doc_json.level = doctor.level;
	    doc_json.information = doctor.information;
	    return Department.findById(doctor.dpt_id).then(function (dept_f) {
		    doc_json.department = dept_f.name;

		    return Hospital.findById(doctor.hp_id);
	    }).then(function (hp_f) {
		    doc_json.address = hp_f.address;

		    res.render('doctor/doctor_detail', {
			    title: '医生信息',
			    user: req.session.user,
			    doctor: doc_json
		    });
	    });
    });
    // res.render('doctor/doctor_detail', {
    //     title: '医生信息',
    //     user: req.session.user
    //
    // });
}).post('/details', function (req, res, next) {
    var doc_id = parseInt(req.query.doc_id);
    var oc_json = [];
	if (isNaN(doc_id)) {
		res.redirect('/');
	}
    Outcalls.findByDoc(doc_id).then(function (outcall) {
        outcall.forEach(function (item) {
            oc_json.push({
	            id:item.dataValues.id,
	            OutCallDate:{
		            Year:item.dataValues.OutCallDate.getFullYear(),
		            Month:item.dataValues.OutCallDate.getMonth() + 1,
		            Day:item.dataValues.OutCallDate.getDay()
	            },
	            OutCallTime:item.dataValues.OutCallTime,
	            Number: item.dataValues.Number,
	            Remain:item.dataValues.Remain,
	            OutCallType:item.dataValues.OutCallType,
	            Status:item.dataValues.Status,
	            fee:item.dataValues.fee,
	            CreateTime:item.dataValues.CreateTime,
	            remark:item.dataValues.remark
            });
        });

        return Doctor.findById(doc_id);
    }).then(function (doctor) {
        var doc_json = {};
        doc_json.name = doctor.name;
        doc_json.level = doctor.level;
        doc_json.information = doctor.information;
        Department.findById(doctor.dpt_id).then(function (dept_f) {
            doc_json.department = dept_f.name;

            return Hospital.findById(doctor.hp_id);
        }).then(function (hp_f) {
            doc_json.address = hp_f.address;

            res.json({
                user: req.session.user,
                outcall: oc_json,
                doctor: doc_json
            });
        });
    });
});

router.get('/appoint', function (req, res, next) {
    if(!req.session.user){
        res.redirect('/user/login');
    }
    else {
        var oc_id = parseInt(req.query.oc_id);
        var doc_id = parseInt(req.query.doc_id);
        var doc_info = {}; //医生信息
        var oc_info= {}; //出诊信息
        var user_info = {}; // 用户信息

        //查找医生信息
        Doctor.findById(doc_id).then(function (doctor) {
            doc_info.doctor_name = doctor.name.toString();
            doc_info.level = doctor.level;
            doc_info.information = doctor.information.toString();
            var hp_id = doctor.hp_id;
            var dpt_id = doctor.dpt_id;
            Hospital.findById(hp_id).then(function (hospital) {
                doc_info.hp_name = hospital.name.toString();
                doc_info.hp_addr = hospital.address.toString();
                return Department.findById(dpt_id).then(function (dpt) {
                    doc_info.dpt_name = dpt.name.toString();
                })
            });

            return Outcalls.findById(oc_id);
        }).then(function (outcall) {
            var date = outcall.OutCallDate.getDate();
            var month = outcall.OutCallDate.getMonth()+1;
            var year = outcall.OutCallDate.getFullYear();
            oc_info.oc_Date = year + '-' + month + '-' + date;
            oc_info.oc_Time = outcall.OutCallTime;
            oc_info.oc_Type = outcall.OutCallType;
            oc_info.oc_fee = outcall.fee;
            return User.findById(req.session.user.id);
        }).then(function (user) {
            user_info.user_name = user.name.toString();
            user_info.user_tel = user.telephoneNumber.toString();
            user_info.user_idnum = user.ID_Number.toString();
            user_info.user_idtype = user.ID_TYPE.toString();

            res.render('doctor/doctor_appoint', {
                title: '医生预约',
                user: req.session.user,
                doctor: doc_info,
                outcall: oc_info,
                user_info: user_info
            });
        });
    }
}).post('/appoint', function (req, res, next) {
    var oc_id = parseInt(req.query.oc_id);
    var user_id = +req.session.user.id;
    if(req.session.user){
        var appointment = {
            user_id: user_id,
            Outcall_id: oc_id,
            createTime: new Date(),
            Status: 1,
            remark: 'default'
        };
        Appointment.UserAppoCount(user_id).then(function (count) {
           if(count > 2) {
               res.send('预约次数超过三次')
           }
           else {
               Appointment.findByOcAndUser(user_id,oc_id).then(function (Appo) {
                   if(!Appo) {
                       Outcalls.findById(oc_id).then(function (outcall) {
                           outcall.decrement({'Remain':1});
                       });
                       Appointment.create(appointment).then(function (appo) {
                           if(appo){
                               res.redirect('/appointment/my')
                               //res.send('create successfully!');
                           }
                       })
                   }
                   else {
                       res.send("You have already appointed!");
                   }
               });

           }
        });
        // Appointment.findByOcAndUser(user_id,oc_id).then(function (Appo) {
        //     if(!Appo) {
        //         Outcalls.findById(oc_id).then(function (outcall) {
        //             outcall.decrement({'Remain':1});
        //         });
        //         Appointment.create(appointment).then(function (appo) {
        //             if(appo){
        //             	res.redirect('/appointment/my')
        //                 //res.send('create successfully!');
        //             }
        //         })
        //     }
        //     else {
        //         res.send("You have already appointed!");
        //     }
        // });

    }
    else {
        //req.flash('info', 'please login');
        res.redirect('/user/login');
    }
});

router.get('/doctor_list_frame', function (req, res, next) {
	var js_object = querystring.parse(url.parse(req.url).query);

	var hid = parseInt(js_object.hid); //医院id

	var fid = parseInt(js_object.fid); //一级科室id
	var sid = parseInt(js_object.sid); //二级科室id
	var dl = parseInt(js_object.dl);   //医生等级

	var pid = parseInt(js_object.pid);//省份
	var cid = parseInt(js_object.cid);//城市
	var aid = parseInt(js_object.aid);//区域

	var list_doctor = []; //医生列表

	if ((!isNaN(hid)) && (!isNaN(fid)) && (!isNaN(sid)) && (!isNaN(dl))) {//通过医院信息和科室信息查找医生

		if (sid === 0) { // 查找该医院，该一级科室，该医生级别的所有医生
			Doctor.findByHospitalFD(hid, fid, dl).then(function (list_doctor_f) {
				list_doctor_f.forEach(function (item) {
					list_doctor.push(item.dataValues);
				});

				res.render('doctor/doctor_list_frame', {
					doc_list: list_doctor
				});
			});
		}
		else { //查找该医院，该二级级科室，该医生级别的所有医生
			Doctor.findByHospitalSD(hid, sid, dl).then(function (list_doctor_f) {
				list_doctor_f.forEach(function (item) {
					list_doctor.push(item.dataValues);
				});

				res.render('doctor/doctor_list_frame', {
					doc_list: list_doctor
				});
			});
		}
	}
	else if ((!isNaN(fid)) && (!isNaN(sid)) && (!isNaN(dl))
		&& (!isNaN(pid)) && (!isNaN(cid)) && (!isNaN(aid))) {//通过地域信息和科室信息查找医生
		if (sid === 0 && aid == 0) {//通过城市和一级科室查找
			async.waterfall([function (callback) {
				async.waterfall([function (callback) {
					Hospital.findByCity(cid).then(function (list_hp_f) {
						callback(null, list_hp_f);
					});
				}, function (list_hp_f, callback) {
					var list_doc = [];
					async.each(list_hp_f, function (item, callback) {
						Doctor.findByHospitalFD(item.dataValues.id, fid, dl).then(function (list_doc_f) {
							list_doc_f.forEach(function (item) {
								list_doc.push(item);
							});
							callback(null);
						});
					}, function (err, result) {
						callback(null, list_doc);
					});
				}], function (err, result) {
					callback(null, result);
				});
			}], function (err, list_doc_f) {
				list_doc_f.forEach(function (item) {
					list_doctor.push(item.dataValues);
				});

				res.render('doctor/doctor_list_frame', {
					doc_list: list_doctor
				});
			});
		}
		else if (sid === 0) {//通过地域和一级科室查找
			async.waterfall([function (callback) {
				async.waterfall([function (callback) {
					Hospital.findByArea(aid).then(function (list_hp_f) {
						callback(null, list_hp_f);
					});
				}, function (list_hp_f, callback) {
					var list_doc = [];
					async.each(list_hp_f, function (item, callback) {
						Doctor.findByHospitalFD(item.dataValues.id, fid, dl).then(function (list_doc_f) {
							list_doc_f.forEach(function (item) {
								list_doc.push(item);
							});
							callback(null);
						});
					}, function (err, result) {
						callback(null, list_doc);
					});
				}], function (err, result) {
					callback(null, result);
				});
			}], function (err, list_doc_f) {
				list_doc_f.forEach(function (item) {
					list_doctor.push(item.dataValues);
				});

				res.render('doctor/doctor_list_frame', {
					doc_list: list_doctor
				});
			});
		}
		else if (aid == 0) {//通过城市和二级科室查找
			async.waterfall([function (callback) {
				async.waterfall([function (callback) {
					Hospital.findByCity(cid).then(function (list_hp_f) {
						callback(null, list_hp_f);
					});
				}, function (list_hp_f, callback) {
					var list_doc = [];
					async.each(list_hp_f, function (item, callback) {
						Doctor.findByHospitalSD(item.dataValues.id, sid, dl).then(function (list_doc_f) {
							list_doc_f.forEach(function (item) {
								list_doc.push(item);
							});
							callback(null);
						});
					}, function (err, result) {
						callback(null, list_doc);
					});
				}], function (err, result) {
					callback(null, result);
				});
			}], function (err, list_doc_f) {
				list_doc_f.forEach(function (item) {
					list_doctor.push(item.dataValues);
				});

				res.render('doctor/doctor_list_frame', {
					doc_list: list_doctor
				});
			});
		}
		else {//通过地域和二级科室查找
			async.waterfall([function (callback) {
				async.waterfall([function (callback) {
					Hospital.findByArea(aid).then(function (list_hp_f) {
						callback(null, list_hp_f);
					});
				}, function (list_hp_f, callback) {
					var list_doc = [];
					async.each(list_hp_f, function (item, callback) {
						Doctor.findByHospitalSD(item.dataValues.id, sid, dl).then(function (list_doc_f) {
							list_doc_f.forEach(function (item) {
								list_doc.push(item);
							});
							callback(null);
						});
					}, function (err, result) {
						callback(null, list_doc);
					});
				}], function (err, result) {
					callback(null, result);
				});
			}], function (err, list_doc_f) {
				list_doc_f.forEach(function (item) {
					list_doctor.push(item.dataValues);
				});

				res.render('doctor/doctor_list_frame', {
					doc_list: list_doctor.sort(function (a, b) {
						return (a.id > b.id);
					})
				});
			});
		}
	}
	else {
		res.redirect('/');
	}
});

module.exports = router;